/**
 * 
 */
package com.mapan.tools.utils;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * @author xinyu162@gmail.com
 * 
 */
public class FileLockProteritesUtil {

	/**
	 * 给文件加锁，后面添加 context
	 * 
	 * @param filePath
	 * @param context
	 */
	public static void addProterites(String filePath, String context) {

		RandomAccessFile out = null;

		FileChannel fileChannel = null;

		FileLock fileLock = null;

		try {
			out = new RandomAccessFile(filePath, "rw");
			fileChannel = out.getChannel();
			fileLock = fileChannel.lock();
			out.seek(out.length());
			out.write((context+"\r\n").getBytes());
		} catch (IOException e) {
		} finally {
			if (fileLock != null) {
				try {
					fileLock.release();
				} catch (IOException e1) {
				}
			}

			if (fileChannel != null) {
				try {
					fileChannel.close();
				} catch (IOException e1) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e1) {
				}
			}

		}

	}
	
	
	
	public static void removeProterites(String filePath, String context) {
		RandomAccessFile out = null;

		FileChannel fileChannel = null;

		FileLock fileLock = null;

		try {
			out = new RandomAccessFile(filePath, "rw");
			fileChannel = out.getChannel();
			fileLock = fileChannel.lock();
			String oldContext = "";
			String tmp = null;
			while ((tmp = out.readLine()) != null) {
				if (tmp.trim().equals(context)) {
				}else {
					if (oldContext.equals("")) {
						oldContext += tmp ;
					}else{
						oldContext += "\r\n" + tmp ;
					}
					
				}
			}
			out.setLength(0);
			out.write(oldContext.getBytes());
		} catch (IOException e) {
		} finally {
			if (fileLock != null) {
				try {
					fileLock.release();
				} catch (IOException e1) {
				}
			}

			if (fileChannel != null) {
				try {
					fileChannel.close();
				} catch (IOException e1) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e1) {
				}
			}

		}

	}
}